package com.example.eazytransfer.ui;

import com.example.eazytransfer.Main;
import com.example.eazytransfer.model.Config;
import com.example.eazytransfer.model.ViewModel;
import com.google.gson.Gson;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import org.apache.commons.io.FileUtils;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;


public class ReceiveFileController implements Initializable {
    @FXML
    private ListView<String> lvReceiveFile;
    @FXML
    private Button btnOpenReceivePath;
    @FXML
    private Label labelReceivingFile;
    @FXML
    private ProgressBar progressBarReceive;
    @FXML
    private Label labelProgressReceive;
    @FXML
    private Label labelReceivePath;
    @FXML
    private Button btnEditReceivePath;

    @FXML
    private Pane root;

    @FXML
    protected void openReceivePath() {
        Desktop desktop = Desktop.getDesktop();
        try {
            desktop.open(new File(ViewModel.getInstance().dirForReceive.get()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    protected void editReceivePath() {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        File file = directoryChooser.showDialog(root.getScene().getWindow());
        if (file == null) return;
        String path = file.getPath();//选择的文件夹路径
        ViewModel.getInstance().dirForReceive.set(path);
        try {
            File file1 = new File(Main.configFile);
            String json = FileUtils.readFileToString(file1,"UTF-8");
            Config config=new Gson().fromJson(json, Config.class);
            config.setReceiveFileDir(path);
            FileUtils.writeStringToFile(file1,new Gson().toJson(config),"UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @FXML
    protected void refreshList() {
        lvReceiveFile.setItems(ViewModel.getInstance().filePathListHasReceive);
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        lvReceiveFile.setItems(ViewModel.getInstance().filePathListHasReceive);
        labelReceivePath.textProperty().bindBidirectional(ViewModel.getInstance().dirForReceive);
        labelReceivingFile.textProperty().bindBidirectional(ViewModel.getInstance().filePathOnReceiving);
        progressBarReceive.progressProperty().bindBidirectional(ViewModel.getInstance().receivingProgress);
        labelProgressReceive.textProperty().bindBidirectional(ViewModel.getInstance().receivingProgressPercent);
        ViewModel.getInstance().filePathOnReceiving.set("无");
        ViewModel.getInstance().receivingProgress.set(0);
        ViewModel.getInstance().receivingProgressPercent.set("0%");
    }
}
